package com.wzy.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @auth wzy
 * @date 2023/10/17 15:24
 */
@Component
@Aspect
public class MyAdvice {

    private static final Logger log = Logger.getLogger(MyAdvice.class);

    @Pointcut("execution(* com.wzy.service..*.*(..))")
    public void pointcut(){

    }

    //前置增强
    @Before("pointcut()")
    public void myBefore(JoinPoint jp){
        log.info("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法。方法的入参为："+ Arrays.toString(jp.getArgs()));
    }

    //后置增强
    @AfterReturning(pointcut = "pointcut()",returning = "result")
    public void myAfterReturning(JoinPoint jp,Object result){
        log.info("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法。返回值："+result);
    }

    public void myError(JoinPoint jp,Exception e){
        log.error(jp.getTarget()+"中"+jp.getSignature().getName()+"方法发生异常："+e);
    }

    public void myAfter(JoinPoint jp){
        log.error(jp.getTarget()+"中"+jp.getSignature().getName()+"方法执行结束");
    }

    public Object aroundLogger(ProceedingJoinPoint jp) throws Throwable{
        try{
            log.info("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法。方法的入参为："+ Arrays.toString(jp.getArgs()));

            // 执行目标方法
            Object result = jp.proceed();

            log.info("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法。返回值："+result);

            return result;
        } catch (Exception e){
            log.error(jp.getTarget()+"中"+jp.getSignature().getName()+"方法发生异常："+e);
            throw e;
        } finally {
            log.error(jp.getTarget()+"中"+jp.getSignature().getName()+"方法执行结束");
        }
    }
}
